package com.digua.iot.confignetwork.utils

import java.net.InetAddress
import java.net.UnknownHostException

class HexUtils {
    companion object {

        fun parseBssid(bytes: ByteArray, offset: Int, count: Int): String {
            val bssidBytes = ByteArray(count)
            System.arraycopy(bytes, offset, bssidBytes, 0, count)
            return parseBssid(bssidBytes)
        }

        fun parseBssid(bssidBytes: ByteArray): String {
            val sb = StringBuilder()
            for (bssidByte in bssidBytes) {
                val k = 0xff and bssidByte.toInt()
                val hexK = Integer.toHexString(k)
                sb.append(if (k < 16) "0$hexK" else hexK)
            }
            return sb.toString()
        }

        fun parseInetAddr(inetAddrBytes: ByteArray, offset: Int, count: Int): InetAddress? {
            var inetAddress: InetAddress? = null
            val sb = java.lang.StringBuilder()
            for (i in 0 until count) {
                sb.append(inetAddrBytes[offset + i].toInt() and 0xff)
                if (i != count - 1) {
                    sb.append('.')
                }
            }
            try {
                inetAddress = InetAddress.getByName(sb.toString())
            } catch (e: UnknownHostException) {
                e.printStackTrace()
            }
            return inetAddress
        }
    }
}